<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="title">个人信息</h2>
      <p class="desc">查看和修改您的个人信息</p>
    </div>

    <!-- 个人信息卡片 -->
    <el-card class="profile-card">
      <div class="profile-content">
        <!-- 左侧头像区 -->
        <div class="avatar-section">
          <el-avatar :size="120" :src="profileData.avatar" class="user-avatar">
            <i class="el-icon-user-solid" style="font-size: 60px;"></i>
          </el-avatar>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadAvatar"
          >
            <el-button size="small" icon="el-icon-upload2" style="margin-top: 12px;">
              更换头像
            </el-button>
          </el-upload>
        </div>

        <!-- 右侧信息区 -->
        <div class="info-section">
          <!-- 查看模式 -->
          <div v-if="!isEditing" class="view-mode">
            <div class="info-group">
              <div class="info-item">
                <span class="info-label">
                  <i class="el-icon-user"></i> 姓名:
                </span>
                <span class="info-value">{{ profileData.name }}</span>
              </div>
            </div>

            <div class="info-group">
              <div class="info-item">
                <span class="info-label">
                  <i class="el-icon-phone"></i> 手机号码:
                </span>
                <span class="info-value">{{ profileData.phone }}</span>
              </div>
            </div>

            <div class="info-group">
              <div class="info-item">
                <span class="info-label">
                  <i class="el-icon-time"></i> 创建时间:
                </span>
                <span class="info-value">{{ profileData.joinDate | formatDate('Y-m-d') }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">
                  <i class="el-icon-check"></i> 账号状态:
                </span>
                <el-tag :type="profileData.status === 'active' ? 'success' : 'info'" size="small">
                  {{ profileData.status === 'active' ? '正常' : '停用' }}
                </el-tag>
              </div>
            </div>

            <div class="action-buttons">
              <el-button type="primary" icon="el-icon-edit" @click="startEdit">
                编辑信息
              </el-button>
            </div>
          </div>

          <!-- 编辑模式 -->
          <div v-else class="edit-mode">
            <el-form :model="editForm" :rules="formRules" ref="editForm" label-width="100px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="editForm.name" placeholder="请输入姓名"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="editForm.phone" placeholder="请输入手机号码"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="新密码" prop="password">
                    <el-input
                      type="password"
                      v-model="editForm.password"
                      placeholder="不修改密码请留空"
                      show-password
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="确认密码" prop="old_password">
                    <el-input
                      type="password"
                      v-model="editForm.old_password"
                      placeholder="再次输入新密码"
                      show-password
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item>
                <el-button type="primary" @click="saveEdit">保存修改</el-button>
                <el-button @click="cancelEdit">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'Profile',
  data() {
    // 确认密码验证
    const validateold_password = (rule, value, callback) => {
      if (this.editForm.password && value === '') {
        callback(new Error('请再次输入密码'));
      } else if (this.editForm.password && value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      // 个人信息数据
      profileData: {
        name: '',
        workNumber: '',
        phone: '',
        email: '',
        department: '',
        title: '',
        bio: '',
        joinDate: '',
        status: '',
        avatar: ''
      },

      // 编辑状态
      isEditing: false,

      // 编辑表单
      editForm: {
        name: '',
        workNumber: '',
        phone: '',
        email: '',
        department: '',
        title: '',
        bio: '',
        password: '',
        old_password: ''
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        password: [
          { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
        ],
        old_password: [
          { validator: validateold_password, trigger: 'blur' }
        ]
      }
    };
  },

  mounted() {
    // 页面加载时获取个人信息
    this.fetchProfile();
  },

  methods: {
    // 获取个人信息
    async fetchProfile() {
      try {
        const res = await api.admin.getAccountDetail()
        if (res.code === 200 && res.data) {
          // 处理头像URL，后端返回的可能是相对路径，需要转换为完整URL
          let avatarUrl = res.data.avatar || ''
          if (avatarUrl && !avatarUrl.startsWith('http://') && !avatarUrl.startsWith('https://')) {
            // 如果不是完整URL，添加基础URL
            // 从VUE_APP_BASE_API提取域名，如果是相对路径则使用window.location.origin
            let baseUrl = process.env.VUE_APP_BASE_API || ''
            if (baseUrl && (baseUrl.startsWith('http://') || baseUrl.startsWith('https://'))) {
              // 提取域名部分（去掉/api等路径）
              baseUrl = baseUrl.replace(/\/api.*$/, '')
            } else {
              // 使用当前页面的域名
              baseUrl = window.location.origin
            }
            avatarUrl = baseUrl + (avatarUrl.startsWith('/') ? '' : '/') + avatarUrl
          }
          
          this.profileData = {
            name: res.data.name || res.data.username,
            workNumber: res.data.username,
            phone: res.data.phone || '',
            email: res.data.email || '',
            department: res.data.department || '',
            position: res.data.position || '',
            avatar: avatarUrl || 'https://picsum.photos/id/1005/120/120',
            joinDate: res.data.created_at || '',
            status: res.data.status === 1 || res.data.status === true || res.data.status === '1' ? 'active' : 'disabled',
            bio: res.data.bio || ''
          }
          
          // 更新缓存中的用户信息
          // 保存原始头像URL（不带时间戳）到缓存
          const userInfoToCache = {
            ...res.data,
            avatar: res.data.avatar || '' // 保存原始头像URL
          }
          localStorage.setItem('userInfo', JSON.stringify(userInfoToCache))
          
          // 触发全局事件通知其他组件更新用户信息
          window.dispatchEvent(new CustomEvent('userInfoUpdated'))
        }
      } catch (error) {
      }
    },

    // 开始编辑
    startEdit() {
      this.editForm = { 
        ...this.profileData,
        password: '',
        old_password: ''
      };
      this.isEditing = true;
    },

    // 保存编辑
    async saveEdit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          try {
            // 获取当前用户ID
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
            
            // 准备提交数据
            const submitData = {
              id: userInfo.id,
              username: this.editForm.workNumber,
              name: this.editForm.name,
              phone: this.editForm.phone,
              is_admin: userInfo.is_admin,
            }

            // 添加可选字段
            if (this.editForm.avatar) submitData.avatar = this.editForm.avatar;

            // 如果填写了新密码，则添加密码字段
            if (this.editForm.password) {
              submitData.password = this.editForm.password;
              submitData.old_password = this.editForm.old_password;
            }
            
            // 调用API保存
            const res = await api.admin.updateAccount(submitData)
            
            if (res.code === 200) {
              this.profileData = { 
                ...this.editForm,
                password: '',
                old_password: ''
              }
              this.isEditing = false
              
              // 根据是否修改了密码显示不同提示
              if (this.editForm.password) {
                this.$message.success('信息和密码修改成功，请重新登录')
                
                // 清除登录信息
                localStorage.removeItem('token')
                localStorage.removeItem('userInfo')
                
                // 3秒后跳转到登录页
                setTimeout(() => {
                  this.$router.push('/login')
                }, 3000)
              } else {
                this.$message.success('个人信息更新成功')
                
                // 更新localStorage中的用户信息
                const updatedUserInfo = {
                  ...userInfo,
                  name: this.editForm.name,
                  username: this.editForm.workNumber,
                  phone: this.editForm.phone,
                  avatar: this.editForm.avatar
                }
                localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
                
                // 触发全局事件通知其他组件更新用户信息
                window.dispatchEvent(new CustomEvent('userInfoUpdated'))
              }
            }
          } catch (error) {
            this.$message.error(error.message || '更新失败，请重试')
          }
        }
      })
    },

    // 取消编辑
    cancelEdit() {
      this.isEditing = false;
      this.$refs.editForm.resetFields();
    },

    // 上传头像前的校验
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    // 自定义上传
    async uploadAvatar(params) {
      const formData = new FormData();
      formData.append('avatar', params.file);

      try {
        const res = await api.auth.uploadAvatar(formData);
        if (res.code === 200 && res.data) {
          // 获取头像URL，优先使用avatar字段，其次url字段
          const avatarUrl = res.data.avatar || res.data.url || res.data;
          
          // 添加时间戳防止缓存
          const timestamp = Date.now();
          const avatarUrlWithTimestamp = avatarUrl + (avatarUrl.includes('?') ? '&' : '?') + '_t=' + timestamp;
          
          // 更新头像显示（使用带时间戳的URL强制刷新）
          this.profileData.avatar = avatarUrlWithTimestamp;
          if (this.isEditing) {
            this.editForm.avatar = avatarUrlWithTimestamp;
          }
          
          // 更新localStorage中的用户信息（直接使用上传接口返回的数据，无需再次请求）
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
          const updatedUserInfo = {
            ...userInfo,
            avatar: avatarUrl // 保存不带时间戳的原始URL
          };
          localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));
          
          // 触发全局事件通知其他组件更新用户信息
          window.dispatchEvent(new CustomEvent('userInfoUpdated'));
          
          this.$message.success('头像上传成功');
        } else {
          this.$message.error(res.message || '头像上传失败');
        }
      } catch (error) {
        const errorMsg = error.response?.data?.message || error.message || '头像上传失败，请重试';
        this.$message.error(errorMsg);
      }
    }
  }
};
</script>

<style scoped>
/* 页面标题 */
.page-header {
  margin-bottom: 20px;
  text-align: left;
}
.title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin-bottom: 5px;
}
.desc {
  color: #86909C;
  font-size: 14px;
}

/* 个人信息卡片 */
.profile-card {
  max-width: 1200px;
}

.profile-content {
  display: flex;
  gap: 40px;
  padding: 20px;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 160px;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

/* 信息区域 */
.info-section {
  flex: 1;
}

/* 查看模式 */
.view-mode {
  width: 100%;
}

.info-group {
  display: flex;
  gap: 40px;
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #F2F3F5;
}

.info-group:last-of-type {
  border-bottom: none;
  margin-bottom: 32px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  flex: 1;
}

.info-item.full-width {
  flex: 1 1 100%;
}

.info-label {
  color: #86909C;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 6px;
}

.info-label i {
  color: #165DFF;
}

.info-value {
  color: #1D2129;
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
}

.action-buttons {
  display: flex;
  gap: 12px;
  padding-top: 8px;
}

/* 编辑模式 */
.edit-mode {
  width: 100%;
}

/* 响应式 */
@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
    gap: 20px;
  }

  .info-group {
    flex-direction: column;
    gap: 16px;
  }
}
</style>
